<template>
  <div class="chart-container" ref="container">
    <div
      :class="!isClick ? 'chart-body' : 'chart-body-click'"
      ref="chartDiv"
      :style="style"
    ></div>
  </div>
</template>

<script>
// 引入防抖函数
import { debounce } from '@/utils'

export default {
  name: 'EchartsTemp',
  props: {
    options: {
      type: Object,
      default() {
        return null
      }
    },
    styles: {
      type: Object,
      default() {
        return {}
      }
    },
    isClick: {
      type: Boolean,
      default: () => {
        return false
      }
    }
  },
  data() {
    return {
      style: {},
      chartObj: null,
      chartData: {},
      chartDom: null,
      resizeHanlder: null
    }
  },
  watch: {
    styles(val) {
      this.style = val
    },
    options() {
      this.drawChart()
    }
  },
  mounted() {
    this.chartDom = this.$refs.chartDiv
    this.chartObj = this.$echarts.init(this.chartDom, 'customTheme')
    this.chartObj.on('click', params => {
      this.itemClick(params)
    })
    this.chartObj.on('legendselectchanged', params => {
      this.legendClick(this.chartObj, params)
    })
    this.drawChart()
    this.resizeHanlder = debounce(this.refreshChart)
    // 添加尺寸改变事件
    window.addEventListener('resize', this.resizeHanlder)
    // this.$bus.$on('toggleSideMenu', this.resizeHanlder);
  },
  activated() {
    // 添加尺寸改变事件
    this.resizeChart()
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.refreshChart)
  },
  methods: {
    // 刷新图表
    refresh() {
      this.drawChart()
    },
    clearChart() {
      this.chartObj.clear()
    },
    resizeChart() {
      let totleHeight = this.$refs['container'].clientHeight
      this.style = { height: totleHeight + 'px' }
      this.refreshChart()
    },
    refreshChart() {
      this.chartObj.resize()
    },
    drawChart() {
      this.clearChart()
      if (this.options && Object.keys(this.options).length > 0) {
        this.chartObj.setOption(this.options)
      }
    },
    setOption(option) {
      this.chartObj.setOption(option)
      this.drawChart()
    },
    itemClick(params) {
      this.$emit('itemClick', params)
    },
    legendClick(chartObj, params) {
      this.$emit('legendClick', chartObj, params)
    },
    setProps(props) {
      if (Object.keys(props).length > 0) {
        for (let key in props) {
          this[key] = props[key]
        }
        this.$nextTick(() => {
          this.resizeChart()
          this.drawChart()
        })
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.chart-container ::v-deep {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;

  .chart-body {
    //禁止鼠标小手
    flex: 1;
  }
  .chart-body > div > canvas:hover {
    // cursor: default;
  }
  .chart-body-click {
    //鼠标小手不禁止
    flex: 1;
  }
}
</style>
